
use serde::{Deserialize, Serialize};
use crate::prelude::{
    options::Options, ControlType, DataType
};
#[cfg(feature = "ssr")]
use super::valid_val_by_data_type;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Parameter {
    //参数名称
    pub name: String,
    //参数标题
    pub caption: String,
    //参数数据类型
    #[serde(default)]
    pub data_type: DataType,
    //编辑类型
    #[serde(default)]
    pub edit_type: ControlType,
    //参数默认值
    pub default_value: crate::prelude::DefaultValue,
    //选项
    #[serde(default)]
    pub options: Option<Options>,
    #[serde(default)]
    pub multiple: bool,
    //界面显示占用网格宽度（1-12）
    pub grid: u8,
}
#[cfg(feature = "ssr")]
impl Parameter {
    pub async fn parse(&self) -> anyhow::Result<()> {
        let v = self.default_value.get_value().await?;
        valid_val_by_data_type(self.data_type.clone(), &v).or_else(|err| {
            Err(anyhow::anyhow!("参数{}的默认值{}不是有效的{}:{}", self.name, v, self.data_type, err))
        })?;
        match self.edit_type {
            ControlType::Select => {
                if self.options.is_none() {
                    anyhow::bail!("Select类型的参数必须有select_items")
                }
            }
            ControlType::TreeSelect | ControlType::Search | ControlType::Textarea => {
                anyhow::bail!("edit_type:{}暂不支持", self.edit_type)
            }
            _ => {}
        }
        if let Some(opts)=self.options.as_ref(){
            match opts {
                Options::Array(vec) => {
                    for v in vec.iter() {
                        valid_val_by_data_type(self.data_type.clone(), v).or_else(|err| {
                            Err(anyhow::anyhow!("参数{}的默认值{}不是有效的{}:{}", self.name, v, self.data_type, err))
                        })?;
                    }
                },
                Options::Map(vec) => {
                    for item in vec.iter() {
                        let val=item.value.as_str();
                        valid_val_by_data_type(self.data_type.clone(), val).or_else(|err| {
                            Err(anyhow::anyhow!("参数{}的默认值{}不是有效的{}:{}", self.name, v, self.data_type, err))
                        })?;
                    }
                },
                Options::Tree(vec) => {
                    for item in vec.iter() {
                        let val=item.key.as_str();
                        valid_val_by_data_type(self.data_type.clone(), val).or_else(|err| {
                            Err(anyhow::anyhow!("参数{}的默认值{}不是有效的{}:{}", self.name, v, self.data_type, err))
                        })?;
                    }
                },
                Options::Fetch(fetch_params) => {
                    let dao=crate::base::get_dao(&fetch_params.table_name)?;
                    let fprops=dao.get_field_props();
                    fprops.iter().find(|fp|fp.name==fetch_params.label_col).ok_or(anyhow::anyhow!("label_col:{}不存在",fetch_params.label_col))?;
                    fprops.iter().find(|fp|fp.name==fetch_params.value_col).ok_or(anyhow::anyhow!("value_col:{}不存在",fetch_params.value_col))?;
                    if let Some(pc)=fetch_params.parent_col.as_ref() {
                        fprops.iter().find(|fp|fp.name.as_str()==pc).ok_or(anyhow::anyhow!("parent_col:{}不存在",pc))?;
                    }
                    if let Some(sc)=fetch_params.search_cols.as_ref() {
                        for col in sc.iter() {
                            fprops.iter().find(|fp|fp.name.as_str()==col).ok_or(anyhow::anyhow!("search_cols:{}不存在",col))?;
                        }
                    }
                },
            }
        }
        Ok(())
    }
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum SelectItems {
    Str(Vec<String>),
    KV(Vec<(String, String)>),
}
